<script lang="ts" setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-message-box.css'
import { login, register } from '@/api/request'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { Lock, User } from '@element-plus/icons-vue'
// 当前路由
const router = useRouter()
// 用户信息store
const userStore = useUserStore()

//--------- 登录 | 注册 表单----------------------

// 登录 注册 界面切换标记变量
const isRegister = ref(false)

// 表单ref绑定变量
const form = ref(null)
// 表单数据ref
const formData = ref({
  username: '',
  password: '',
  repassword: ''
})

// 注册回调
const registerUser = async () => {
  // 注册前校验数据是否合法
  await form.value.validate()
  // 发送注册请求
  await register(formData.value)

  ElMessage({
    message: '注册成功',
    grouping: true,
    type: 'success'
  })
  clearFormData()
  isRegister.value = false
}

const userLogin = async () => {
  // 登录前校验数据是否合法
  await form.value.validate()
  // 发送登录请求
  const { token } = await login(formData.value)
  // 将token存入pinia配合插件持久化进localstorge
  userStore.setToken(token)

  // 用户交互
  ElMessage({
    message: '登录成功',
    grouping: true,
    type: 'success'
  })

  clearFormData()
  // 跳转首页
  await router.push('/home')
}

// 清空表单数据的回调
const clearFormData = () => {
  console.log('清除前', formData.value)
  // form.value.resetFields()
  formData.value = {
    username: '',
    password: '',
    repassword: ''
  }
  console.log('清除后', formData.value)
}
// 监听 登录 | 注册界面的切换 一切换 清空表单数据
watch(isRegister, (value) => {
  console.log(value)
  clearFormData()
})

// 自定义表单规则
const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    {
      min: 5,
      max: 10,
      message: '用户名长度应在5-10位',
      trigger: 'change'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      pattern: /^\S{6,15}$/,
      message: '密码格式应为非空的6-15位',
      trigger: 'change'
    }
  ],
  repassword: [
    {
      required: true,
      message: '请二次输入密码',
      trigger: 'blur'
    },
    {
      pattern: /^\S{6,15}$/,
      message: '密码格式应为非空的6-15位',
      trigger: 'blur'
    },
    {
      // 自定义验证规则
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          // 验证失败 回调中返回错误信息
          callback(new Error('二次密码输入不一致'))
          return
        }
        // 验证通过 调用回调放行
        callback()
      },
      trigger: 'blur'
    }
  ]
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form
        :model="formData"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formData.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formData.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
            v-model="formData.repassword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="registerUser"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form
        :model="formData"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formData.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formData.password"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="userLogin"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped lang="less">
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
